package Myfun;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-06-21
 * Time: 9:43
 */
public class MyBlockingQueue {
    public static int count;
    public int rear;
    public int front;
    public int size = 0;
    public int[] array;

    public MyBlockingQueue(int Capacity) {
        this.array = new int[Capacity];
    }
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while(size >= array.length) {
                this.wait();
            }
            array[rear] = value;
            rear = (rear+1) % array.length;
            size++;
            //唤醒take线程的阻塞
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized(this) {
            while(size == 0) {
                this.wait();
            }
            int ret = array[front];
            front = (front+1) % array.length;
            size--;
            //唤醒put线程的阻塞
            this.notify();
            return ret;
        }
    }
    //生产者消费者模型
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(100);
        //消费者1
        Thread t1 = new Thread(() -> {
                try {
                    while (true) {
                        Thread.sleep(1000);
                        myBlockingQueue.take();
                        System.out.println("消费者消费了一个："+ count);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
        });
        //消费者2
        Thread t2 = new Thread(() -> {
                try {
                    while (true) {
                        Thread.sleep(1000);
                        myBlockingQueue.take();
                        System.out.println("消费者消费了一个："+ count);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                    }
        });
        //生产者
        Thread t3 = new Thread(() -> {
                try {
                    while(true) {
                        myBlockingQueue.put(count);
                        System.out.println("生产者生产一个："+ count);
                        count++;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
        });
        //t1.start();
        t2.start();
        t3.start();
    }
}
